package com.tang.common.filter;

import com.tang.common.constant.ParamName;
import com.tang.common.utils.cache.ParamCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.FilterInvocation;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * 权限控制，判断用户角色
 * @author tang
 * @date 2021/11/1 14:34
 */
@Component
@Slf4j
public class AccessDecisionManagerConfig implements AccessDecisionManager {


    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
        //获得过滤器
        FilterInvocation filterInvocation = (FilterInvocation) object;
        //获得请求
        log.info("请求url : {}",filterInvocation.getRequest().getRequestURI());
        log.info("可以访问的角色 : {}",configAttributes);
        for (ConfigAttribute configAttribute : configAttributes) {
            //是否登录了，未经认证的用户分配一个AnonymousAuthenticationToken身份
            if (authentication instanceof AnonymousAuthenticationToken){
                throw new AccessDeniedException("未登录，请先登录");
            }
            //获取读取url所需的角色
            String needRole = configAttribute.getAttribute();
            //是否为其他url,在UrlFilterConfig设置了
            String defaultRole = ParamCache.getValue(ParamName.DEFAULT_ROLE);
            //如果该URL默认用户都可以访问
            if (needRole.equals(defaultRole)){
                return;
            }
            //获得当前登录用户的角色
            log.info("当前拥有角色 : {}",authentication.getAuthorities());
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            for (GrantedAuthority authority : authorities) {
                if (authority.toString().equals(needRole)) {
                    return;
                }
            }
        }
        throw new AccessDeniedException("接口权限不足,请联系管理员");
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return false;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return false;
    }
}
